//Copyright (c) 2010, Goodwine & Tibia ML
//Licensed under new BSD License.

// Load options.
getLocalStorageValue('indicator');

// Track how often people clicks hide/show offline.
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-18344881-2']);
_gaq.push(['_trackPageview']);
(function() {
	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	ga.src = 'https://ssl.google-analytics.com/ga.js';
	var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
function _trackButton(id, option) {
	_gaq.push(['_trackEvent', id, JSON.stringify(option)]);
}
var tmlIcon, exhIcon;
var guild = document.getElementsByTagName('body');
guild = guild[0].innerHTML;
var original;
var updateCheck = false;
var hide = 0;
// Check if guild should be checked.
if(guild.match(/It is currently active/ig))
{
	world = guild.match(/The guild was founded on (.*?) on/);
	world = world[1];
	chrome.extension.sendRequest({'world' : world}, playerListGuild);
	// Icon link Characters.
	if(opLinkPages.guild)
		chrome.extension.sendRequest({action : 'loadJQuery'}, function(data) {
			if (data != null) {
				eval(data);
				$('td a[href*=?subtopic=characters&name=]').each(function() {
					this.parentNode.noWrap = true;
					linkCharacter(this.parentElement, this.innerText, 'left');
				});
			} 
			else
				console.warn('Linker: Failed to load jQuery');
		});
}

// Script to hide/show offline to be injected.
var scriptHideUnhide = function ()
{
	var members = document.getElementsByTagName("tbody");
	for(i=1; i < members.length; i++)
	{
		if(members[i].innerHTML.match(/<b>Guild Members<\/b>/ig))
		{
			members = members[i].getElementsByTagName("tr");
			break;
		}
	}
	var temp;
	var indicator = sessionStorage.getItem('indicator');
	_trackButton('Guild Online', this.getAttribute("membershidden") == 0 ? 'hide' : 'show');
	if(this.getAttribute("membershidden") == 0)
	{
		this.setAttribute("membershidden", "1");
		this.innerHTML = "[Show Offline]";
		this.setAttribute("class", "red");
		if(indicator == 'none')
		{
			var lvlvoc = document.getElementsByClassName('lvlvoc');
			for(var i=0; i<lvlvoc.length; i++)
			{
				lvlvoc[i].style.display = "";
			}
		}
		for(var i=1, rankWasSet = false; i < members.length; i++)
		{
			if(members[i].getAttribute("hasRank") == 1)
			{
				lastRank = members[i].getAttribute("thisRank");
				rankWasSet = false;
			}
			if(members[i].getAttribute("online") == 0)
			{
				members[i].style.display = "none";
			}
			else
			{
				if(members[i].getAttribute("hasRank") == 0 && !rankWasSet)
				{
					var fc = members[i].firstChild;
					members[i].setAttribute("wasModified", 1);
					fc.innerHTML = "<rankTag>"+members[i].getAttribute("thisRank")+"</rankTag>"+members[i].firstChild.innerHTML;
					rankWasSet = true;
				}
				else if(!rankWasSet)
				{
					rankWasSet = true;
				}
			}
		}
	}
	else
	{
		this.innerHTML = "[Hide Offline]";
		this.setAttribute("membershidden", 0);
		this.setAttribute("class", "green");
		if(indicator == 'none')
		{
			var lvlvoc = document.getElementsByClassName('lvlvoc');
			for(var i=0; i<lvlvoc.length; i++)
			{
				lvlvoc[i].style.display = "none";
			}
		}
		for(var i = 1; i < members.length; i++)
		{
			if(members[i].getAttribute("wasModified") == 1)
			{
				members[i].firstChild.removeChild(members[i].firstChild.firstChild);
				members[i].setAttribute("wasModified", 0)
			}
			if(members[i].getAttribute("online") == 0)
				members[i].style.display = "";
		}
	}
}

// Automatically update Online status.
function autoUpdateGuild()
{
	updateCheck = true;
	hide = document.getElementById('hideUnhideScript').getAttribute("membershidden");
	chrome.extension.sendRequest({'world' : world}, playerListGuild);
}

// XHR to get characters online, parse them and compare.
function playerListGuild(data)
{
	if (data != null)
	{
		var players = [];
		var pattern =/subtopic=characters&name=.*?>(.*?)<\/A><\/TD><TD.*?>(.+?)<\/TD><TD.*?>(.+?)<\/TD><\/TR>/img;
		var matches = 0;
		var voc = "?";
		var x;
		var i;
		while((x = pattern.exec(data)) != null)
		{
			players[matches] = [];
			players[matches][0] = x[1].replace(/(\xa0|&#160;|&nbsp;| )/g, ' ');// name
			players[matches][1] = x[2]; // lvl
			voc = x[3].replace(/(\xa0|&#160;|&nbsp;| )/ig, ' ');
			if (voc == 'Knight')                  voc = 'K';
				else if (voc == 'Elite Knight')    voc = 'EK';
				else if (voc == 'Paladin')         voc = 'P';
				else if (voc == 'Royal Paladin')   voc = 'RP';
				else if (voc == 'Sorcerer')        voc = 'S';
				else if (voc == 'Master Sorcerer') voc = 'MS';
				else if (voc == 'Druid')           voc = 'D';
				else if (voc == 'Elder Druid')     voc = 'ED';
				else if (voc == 'None')            voc = 'ROOK';
				else                               voc = '?';
			players[matches][2] = voc; // voc
			matches++;
		}
		var members = document.getElementsByTagName('tbody');
		for(i=1; i < members.length; i++)
		{
			if(members[i].innerHTML.match(/<b>Guild Members<\/b>/i))
			{
				if(updateCheck == false)
					original = members[i].innerHTML;
				else
					members[i].innerHTML = original;
				members = members[i].getElementsByTagName('td');
				break;
			}
		}
		var pattern2 = /subtopic=characters&.*?name=.*?>(.*?)</ig;
		var count = 0;
		var oncount = 0;
		for(i=1; i < members.length; i++)
		{
			members[i].noWrap = true;
			if((x = pattern2.exec(members[i].innerHTML)) != null)
			{
				var lastRank;
				if (members[i-1].innerHTML.match(/^(\xa0|&#160;|&nbsp;| )$/ig))
					members[i].parentNode.setAttribute("hasRank", 0);
				else
				{
					members[i].parentNode.setAttribute("hasRank", 1);
					lastRank = members[i-1].innerText;
				}
				members[i].parentNode.setAttribute("thisRank", lastRank);
				members[i].parentNode.setAttribute("wasModified", 0);
				count++;
				var on = false;
				for(j=0;j<players.length;j++)
				{
					x[1] = x[1].replace(/(\xa0|&#160;|&nbsp;| )/ig, ' ');
					if(x[1] == players[j][0])
					{
						members[i-1].appendChild(onlineIndicator());
						members[i-1].appendChild(lvlVoc(players[j][1],players[j][2]));
						oncount++;
						members[i].parentNode.setAttribute('online',1);
						on=true
					}
				}
				if(!on)
				{
					members[i-1].appendChild(offlineIndicator());
					members[i].parentNode.setAttribute('online',0);
				}  
			}
		}
		var link = document.createElement('a');
		link.href = 'javascript:;';
		link.setAttribute('membershidden', 0);
		link.innerText = '[Hide Offline]';
		link.setAttribute('class', 'green');
		link.setAttribute('id', 'hideUnhideScript');
		link.onclick = scriptHideUnhide;
		link.style.paddingLeft = "5px";
		
		var span = document.createElement('span');
		span.style.fontSize = "9px";
		span.style.verticalAlign = "middle";
		span.style.paddingRight = "5px";
		span.style.float = "right";
		span.innerHTML = 'Guild Members: '+count+' (Online: '+oncount+') &nbsp; Online on '+world+': '+players.length;
		members[0].appendChild(link);
		members[0].appendChild(span);
		
		if(hide == 1 && updateCheck)
		{
			var lvlvoc = document.getElementsByClassName('lvlvoc');
			for(var i=0; i<lvlvoc.length; i++)
			{
				lvlvoc[i].style.display = "";
			}
			var members = document.getElementsByTagName('tbody');
			for(i=1; i < members.length; i++)
			{
				if(members[i].innerHTML.match(/<b>Guild Members<\/b>/i))
				{
					members = members[i].getElementsByTagName("tr");
					break;
				}
			}
			document.getElementById('hideUnhideScript').setAttribute("membershidden", "1");
			document.getElementById('hideUnhideScript').innerHTML = "[Show Offline]";
			document.getElementById('hideUnhideScript').setAttribute("class", "red");
			for(var i=1, rankWasSet = false; i < members.length; i++)
			{
				if(members[i].getAttribute("hasRank") == 1)
				{
					lastRank = members[i].getAttribute("thisRank");
					rankWasSet = false;
				}
				if(members[i].getAttribute("online") == 0)
				{
					members[i].style.display = "none";
				}
				else
				{
					if(members[i].getAttribute("hasRank") == 0 && !rankWasSet)
					{
						var fc = members[i].firstChild;
						members[i].setAttribute("wasModified", 1);
						fc.innerHTML = "<rankTag>"+members[i].getAttribute("thisRank")+"</rankTag>"+members[i].firstChild.innerHTML;
						rankWasSet = true;
					}
					else if(!rankWasSet)
					{
						rankWasSet = true;
					}
				}
			}
		}
		setTimeout('autoUpdateGuild()', reloadTime(5));
	}
}

// Sets the online indicator according to options.
function onlineIndicator()
{
	var indicator;
	var none = document.createElement('div');
	none.style.width = 0;
	none.style.height = 0;
	none.style.display = 'none';
	indicator = sessionStorage.indicator ? sessionStorage.indicator : 'icon';
	switch(indicator)
	{
		default:
		case 'icon':
			var img = document.createElement('img');
			img.alt="Online";
			img.title="Online";
			img.style.height = "16px";
			img.style.padding = 0;
			img.style.color = "green";
			img.style.float = "right";
			img.src = chrome.extension.getURL("/images/green icon.svg");
			return img;
		break;
		
		case 'text':
			var span = document.createElement('span');
			span.style.color = 'green';
			span.style.verticalAlign = "middle";
			span.style.float = 'right';
			span.style.fontWeight = 'bold';
			span.style.padding = 0;
			span.innerText = "On";
			return span;
		break;
		
		case 'none':
			return none;
	}
}

// Sets the offline indicator according to options.
function offlineIndicator()
{
	var indicator;
	var none = document.createElement('div');
	none.style.width = 0;
	none.style.height = 0;
	none.style.display = 'none';
	indicator = sessionStorage.indicator ? sessionStorage.indicator : 'icon';
	switch(indicator)
	{
		default:
		case 'icon':
			var img = document.createElement('img');
			img.alt="Offline";
			img.title="Offline";
			img.style.height = "16px";
			img.style.padding = 0;
			img.style.color = "red";
			img.style.float = "right";
			img.src = chrome.extension.getURL("/images/gray icon.svg");
			return img;
		break;
		
		case 'text':
		case 'none':
			return none;
	}
}

// Sets a div element with level and voc.
function lvlVoc(lvl, voc) {
	var span = document.createElement('span');
	span.className = "lvlvoc";
	span.style.paddingRight = "7px";
	span.style.verticalAlign = "middle";
	span.style.fontSize = '9px';
	span.style.float = 'right';
	span.innerText = "Lv:"+lvl+" Voc:"+voc;
	var indicator;
	indicator = sessionStorage.indicator;
	if(indicator == 'none')
		span.style.display = "none";
	return span;
}